package com.longxi.tianjintianbao.ui.presenter.repair;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.model.Personnel;
import com.longxi.tianjintianbao.model.RepairDetail;
import com.longxi.tianjintianbao.model.repair.RepairAssets;
import com.longxi.tianjintianbao.ui.activity.assetscheck.TestActivity;
import com.longxi.tianjintianbao.ui.activity.repair.CompleteEventRepairActivity;
import com.longxi.tianjintianbao.ui.activity.repair.UpdateRepairContentActivity;
import com.longxi.tianjintianbao.ui.activity.scan.ScanActivity2;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.repair_publish.IRepairDetailAtView;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.widget.MaintenancePlanDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class RepairDetailAtPresenter extends BasePresenter<IRepairDetailAtView> {

    private RepairDetail repairDetail;//单据内容
    private String billid;//单据id
    private boolean isUpdate = false;
    private int function = 1;
    private List<LocalMedia> selectList = new ArrayList<>();

    List<Personnel> personnelListIntent = new ArrayList<>();//回传的角色值

    public RepairDetailAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        mContext.setTitle("报修详情");
        mContext.setTvLeft(MyUtils.getString(R.string.back));
    }

    /**
     * 获取报修详情
     */
    public void getData() {
        Intent intent = mContext.getIntent();
        billid =intent.getStringExtra(AppConst.BILLID);

        JSONObject object = new JSONObject();
        try {
            object.put("billid", billid);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        ApiRetrofit.getInstance().getEventRepair(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<RepairDetail>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<RepairDetail> repairDetailResponse) {
                fjData(repairDetailResponse);
//                if(MainActivity.mainActivity != null){
//                    MainActivity.mainActivity.refreshHomeMessage();
//                }
            }
        });
    }

    private void fjData(HttpResult<RepairDetail> repairDetailResponse) {
        mContext.hideWaitingDialog();
        if(repairDetailResponse.getCode() != 0){
            MyUtils.showToast(repairDetailResponse.getMsg());
            return;
        }
        repairDetail = repairDetailResponse.getData().get(0);
        repairDetail.setBillid(billid);
        if(repairDetail == null){
            MyUtils.showToast("详情数据异常");
            return;
        }
        getView().getTvName().setText(repairDetail.getContacts());
        getView().getTvAddress().setText(repairDetail.getBuildname() + " " + repairDetail.getAddress());
        getView().getTvRepairArea().setVisibility(View.GONE);
//        getView().getTvRepairArea().setText("维修区域:" + repairDetail.getRegion() + " 类型:" + repairDetail.getRepairtype() + " 类别:" + repairDetail.getRepaircategory());

        getView().getTvRepairContent().setText(repairDetail.getContent());
        getView().getTvTime().setText("发布时间: " + repairDetail.getBilldate());
        getView().getTvProgress().setText(repairDetail.getState());
//        getView().getTvArrangedate().setText("预约时间: " + repairDetail.getArrangedate() + "\n维修区域: " + repairDetail.getRegion() + "\n维修类型: " + repairDetail.getRepairtype() + "\n维修类别: " + repairDetail.getRepaircategory());
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("维修区域: " + repairDetail.getRegion());
        stringBuffer.append("\n维修类型: " + repairDetail.getRepairtype());
        stringBuffer.append("\n维修类别: " + repairDetail.getRepaircategory());
        stringBuffer.append("\n客户类型: " + ("1".equals(repairDetail.getCusttype()) ? "员工" : "租户"));
        stringBuffer.append("\n预计完成时间: " + repairDetail.getArrangedate());
        stringBuffer.append("\n派单时间: " + repairDetail.getSenddate() + " 派单人: " + repairDetail.getSender());
        stringBuffer.append("\n接单时间: " + repairDetail.getReceiptdate() + " 接单人: " + repairDetail.getReceipter());
        stringBuffer.append("\n开始时间: " + repairDetail.getStartdate());
        stringBuffer.append("\n回访时间: " + repairDetail.getVisitdate() + " 回访人: " + repairDetail.getVisiter());
        stringBuffer.append("\n回访情况: " + repairDetail.getCustadvice());
        stringBuffer.append("\n满意度: " + repairDetail.getCustevaluate());
        stringBuffer.append("\n维修方案: " + repairDetail.getScheme());
        stringBuffer.append("\n维修材料: " + repairDetail.getMaterial());
        stringBuffer.append("\n资产编号: " + repairDetail.getAssetscode());
        stringBuffer.append("\n资产名称: " + repairDetail.getAssetsname());
        getView().getTvArrangedate().setText(stringBuffer);
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.mipmap.ic_load_image)
                .error(R.mipmap.ic_error_image);
        if(!"".equals(repairDetail.getImage1())){
            getView().getIvImage1().setVisibility(View.VISIBLE);
            Glide.with(mContext)
                    .asBitmap()
                    .apply(options)
                    .load(repairDetail.getImage1())
                    .into(getView().getIvImage1());
            selectList.add(new LocalMedia(repairDetail.getImage1(), 0, 0, ""));
            getView().getIvImage1().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PictureSelector.create(mContext).themeStyle(R.style.picture_default_style).openExternalPreview(0, selectList);
                }
            });
        }
        if(!"".equals(repairDetail.getImage2())){
            getView().getIvImage2().setVisibility(View.VISIBLE);
            Glide.with(mContext)
                    .asBitmap()
                    .apply(options)
                    .load(repairDetail.getImage2())
                    .into(getView().getIvImage2());
            selectList.add(new LocalMedia(repairDetail.getImage2(), 0, 0, ""));
            getView().getIvImage2().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PictureSelector.create(mContext).themeStyle(R.style.picture_default_style).openExternalPreview(1, selectList);
                }
            });
        }
        if(!"".equals(repairDetail.getImage3())){
            getView().getIvImage3().setVisibility(View.VISIBLE);
            Glide.with(mContext)
                    .asBitmap()
                    .apply(options)
                    .load(repairDetail.getImage3())
                    .into(getView().getIvImage3());
            selectList.add(new LocalMedia(repairDetail.getImage3(), 0, 0, ""));
            getView().getIvImage3().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PictureSelector.create(mContext).themeStyle(R.style.picture_default_style).openExternalPreview(1, selectList);
                }
            });
        }
        if(!"".equals(repairDetail.getImage4())){
            getView().getIvImage4().setVisibility(View.VISIBLE);
            Glide.with(mContext)
                    .asBitmap()
                    .apply(options)
                    .load(repairDetail.getImage4())
                    .into(getView().getIvImage4());
            selectList.add(new LocalMedia(repairDetail.getImage4(), 0, 0, ""));
            getView().getIvImage4().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PictureSelector.create(mContext).themeStyle(R.style.picture_default_style).openExternalPreview(1, selectList);
                }
            });
        }

        refreshUI(repairDetail.getState());
    }

    /**
     * 到报修修改页
     */
    public void toUpdateRepairContentActivity() {
        Intent mainIntent = new Intent(mContext, UpdateRepairContentActivity.class);
        mainIntent.putExtra(UpdateRepairContentAtPresenter.REPAIRDETAIL,repairDetail);
        mContext.startActivityForResult(mainIntent, AppConst.IntentRequstCode.ACTIVITY_UPDATE_REPAIR_CONTENT);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != mContext.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case AppConst.IntentRequstCode.ACTIVITY_UPDATE_REPAIR_CONTENT:
                selectList = new ArrayList<>();
                getData();
                break;
            case AppConst.IntentRequstCode.ACTIVITY_PERSONNEL:
                if(data != null){
                    personnelListIntent = (List<Personnel>) data.getSerializableExtra(AppConst.PERSONNEL_LISTINTENT);
                    dispatchEventRepair(personnelListIntent.get(0).getUserid(), personnelListIntent.get(0).getUsername());
                }
                break;
            case AppConst.IntentRequstCode.ACTIVITY_COMPLETE_EVENT_REPAIR:
                getData();
                break;
            case AppConst.IntentRequstCode.REQUEST_CODE_SCAN:
                if (data != null) {
                    if (null != data) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            return;
                        }
                        if (bundle.getInt(AppConst.RESULT_TYPE) == AppConst.RESULT_SUCCESS) {
                            String result = bundle.getString(AppConst.RESULT_STRING);
                            MyUtils.showToast(result);
                            getRepairAssets(result);
                        } else if (bundle.getInt(AppConst.RESULT_TYPE) == AppConst.RESULT_FAILED) {
                            MyUtils.showToast("解析二维码失败");
                        }
                    }
                }
                break;
        }
    }

    private void getRepairAssets(String assetscode) {
        JSONObject object = new JSONObject();
        try {
            object.put("assetscode", assetscode);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        ApiRetrofit.getInstance().getRepairAssets(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<RepairAssets>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<RepairAssets> result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }
                RepairAssets repairAssets = result.getData().get(0);
                repairDetail.setAssetscode(repairAssets.getAssetscode());
                repairDetail.setAssetsname(repairAssets.getAssetsname());

            }
        });
    }

    String content;

    /**
     * 更新列表页数据
     */
    public void RemindPreviousrefresh() {
        if(isUpdate){
            Intent intent = new Intent();
            intent.putExtra("content", content);
            mContext.setResult(Activity.RESULT_OK, intent);
        }
        mContext.finish();
    }

    public void refreshUI(String state){
        getView().getLlState0().setVisibility(View.GONE);
        getView().getLlState1().setVisibility(View.GONE);
        getView().getLlState2().setVisibility(View.GONE);
        getView().getLlState3().setVisibility(View.GONE);
        getView().getLlCannot().setVisibility(View.GONE);

        switch (state) {
            case "未派单":
                getView().getLlState0().setVisibility(View.VISIBLE);
                break;
            case "未接单":
                getView().getLlState1().setVisibility(View.VISIBLE);
                break;
            case "已接单":
                getView().getLlState2().setVisibility(View.VISIBLE);
                break;
            case "维修中":
                function = 1;
                getView().getBtnPause().setText("暂停");
                getView().getLlState3().setVisibility(View.VISIBLE);
                break;
            case "已暂停":
                function = 0;
                getView().getBtnPause().setText("继续");
                getView().getLlState3().setVisibility(View.VISIBLE);
                break;
            case "已完成":
                break;
            case "已回访":
                break;
        }
    }

    /**
     * 接单
     */
    public void order() {
        JSONObject object = new JSONObject();
        try {
            object.put("billid", billid);
            object.put("userid", MyApplication.loginUser.getUserid());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        ApiRetrofit.getInstance().acceptEventRepair(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
//                if(baseResponse.getCode() != 0){
//                    MyUtils.showToast(baseResponse.getMsg());
//                    return;
//                }
                getData();
            }
        });
    }

    /**
     * 开始
     */
    public void start() {
        JSONObject object = new JSONObject();
        try {
            object.put("billid", billid);
            object.put("userid", MyApplication.loginUser.getUserid());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        ApiRetrofit.getInstance().startEventRepair(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                getData();
            }
        });
    }

    /**
     * 报事报修暂停（开始）
     */
    public void pauseAndStart() {
        JSONObject object = new JSONObject();
        try {
            object.put("billid", billid);
            object.put("userid", MyApplication.loginUser.getUserid());
            object.put("function", function);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        ApiRetrofit.getInstance().suspendEventRepair(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                getData();
            }
        });
    }

    /**
     * 报事报修暂停（开始）
     */
    public void complete() {
        Intent intent = new Intent(mContext, CompleteEventRepairActivity.class);
        intent.putExtra(AppConst.BILLID, billid);
        mContext.startActivityForResult(intent, AppConst.IntentRequstCode.ACTIVITY_COMPLETE_EVENT_REPAIR);
    }


    public void repairAreaJudgment(){
        if(TextUtils.isEmpty(repairDetail.getRegion())){
            MyUtils.showToast("请在调整信息中选择维修区域");
            return;
        }

        if(TextUtils.isEmpty(repairDetail.getRepairtype())){
            MyUtils.showToast("请在调整信息中选择维修类型");
            return;
        }

        if(TextUtils.isEmpty(repairDetail.getRepaircategory())){
            MyUtils.showToast("请在调整信息中选择维修类别");
            return;
        }

        getDepartment(false);
    }
    /**
     * 派单
     */
    public void dispatchEventRepair(String repairuserid, String repairusername){

        if("".equals(repairuserid) || repairuserid == null) {
            MyUtils.showToast("请指派维修人员");
            return;
        }

        if("".equals(billid) || billid == null) {
            MyUtils.showToast("单据不存在");
            return;
        }

        JSONObject object = new JSONObject();
        try {
            object.put("billid", billid);
            object.put("dispatchuserid", MyApplication.loginUser.getUserid());
            object.put("dispatchusername", MyApplication.loginUser.getUsername());
            object.put("repairuserid", repairuserid);
            object.put("repairusername", repairusername);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        ApiRetrofit.getInstance().dispatchEventRepair(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                mContext.setResult(Activity.RESULT_OK);
                getData();
            }
        });
    }

    public void scan() {
        AndPermission.with(mContext)
                .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE)
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Intent intent = new Intent(mContext, ScanActivity2.class);
                        mContext.startActivityForResult(intent, AppConst.IntentRequstCode.REQUEST_CODE_SCAN);
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Uri packageURI = Uri.parse("package:" + mContext.getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                        mContext.startActivity(intent);

                        MyUtils.showToast("没有权限无法扫描");
                    }
                }).start();
    }

    MaintenancePlanDialog.Builder maintenancePlanDialog;
    public void plan() {
        if(maintenancePlanDialog != null){
            maintenancePlanDialog.create().show();
        }else{
            maintenancePlanDialog = new MaintenancePlanDialog.Builder(mContext);
            maintenancePlanDialog
            .setProperty(new MaintenancePlanDialog.OnClickListener() {
                @Override
                public void onClick(String estimatedate, String scheme, String material) {
                    dispatchEventRepair(estimatedate, scheme, material);
                    maintenancePlanDialog.dismiss();
                }
            })
            .create()
            .show();
        }
    }

    /**
     * 派单
     */
    public void dispatchEventRepair(String estimatedate, String scheme, String material){

        JSONObject object = new JSONObject();
        try {
            object.put("billid", billid);
            object.put("userid", MyApplication.loginUser.getUserid());
            object.put("estimatedate", estimatedate);
            object.put("scheme", scheme);
            object.put("material", material);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        ApiRetrofit.getInstance().eventRepairPlan(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                mContext.setResult(Activity.RESULT_OK);
                getData();
            }
        });
    }

    public void updateEventRepair() {
        long userid = MyApplication.loginUser.userid;
        String region = "";

        if("".equals(content) || content == null){
            MyUtils.showToast("请输入维修内容");
            return;
        }

        if(!"".equals(dateTime)){
            repairDetail.setArrangedate(dateTime);
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", repairDetail.getBillid());
            object.put("userid", userid);
            if("客户区域".equals(repairDetail.getRegion())){
                region = "0";
            }else if("公共区域".equals(repairDetail.getRegion())){
                region = "1";
            }
            object.put("region", region);
            object.put("repairtype", repairDetail.getRepairtype());
            object.put("repaircategory", repairDetail.getRepaircategory());
            object.put("addressid", repairDetail.getAddressid());
            object.put("address", repairDetail.getAddress());
            object.put("contacts", repairDetail.getContacts());
            object.put("contactsid", repairDetail.getAddressid());
            object.put("contactsphone", repairDetail.getContactsphone());
            object.put("content", content);

            object.put("image1", "");
            object.put("image2", "");
            object.put("imagereplace", "");
            object.put("arrangedate", repairDetail.getArrangedate());
            object.put("assetscode", repairDetail.getAssetscode());
            object.put("assetsname", repairDetail.getAssetsname());
            object.put("custtype", repairDetail.getCusttype());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().saveEventRepair(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                mContext.setResult(Activity.RESULT_OK);

            }
        });
    }

}
